package com.zephyr.vchcenter.pbcFile.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.zephyr.vchcenter.helper.HibernateSessionFactory;
import com.zephyr.vchcenter.helper.SpringHelper;
import com.zephyr.vchcenter.bean.BaseObject;
import com.zephyr.vchcenter.bean.PbcOriginalData;
import com.zephyr.vchcenter.dao.IBaseDao;
//import com.zephyr.vchcenter.dao.impl.BaseDaoJbpmImpl;
import com.zephyr.vchcenter.pbcFile.exception.RepeatException;

/**
 * @author zhaoyunxiao �����ļ�������
 */
public class SingleLineParser {
	private static final Logger log = Logger.getLogger(SingleLineParser.class);
	/**
	 * @param lineStr
	 * @param properties  �����б�
	 * @param regex
	 * @param baseObject
	 * @param format
	 * */
	public Map<String, Object> parse(String lineStr, List<String> properties,
			String regex, BaseObject baseObject, Integer format) {
		// log.debug("enter:singleLineParser:parse.........");
		Pattern p = Pattern.compile(regex);
		Matcher matcher = p.matcher(lineStr);
		boolean flag = matcher.find();
		Map<String, Object> map = new HashMap<String, Object>();
		if (flag){
			//对匹配的数据进行处理
			if (format == null) {
				//format为null说明该文件是单行有分割形式
				int j = 0;
				for (int i = 1; i < matcher.groupCount() + 1; i++) {
					if ((i + 1) % 2 == 0 && j < properties.size()) {
						String key = properties.get(j);
						String value = matcher.group(i);
						map.put(key, value);
						j++;
					}
				}

			}else{
				//format不为null说明为单行无分割格式
			    int j=0;
				for(int i=1;i< matcher.groupCount()+1;i++){
					j++;
					String key=properties.get(i-1);
					String value = matcher.group(i);
					map.put(key, value);
				}
			}
		} else {
			//对无法匹配的数据进行处理
			PbcOriginalData pbcOriginalData = new PbcOriginalData();
			pbcOriginalData.setSubno(((PbcOriginalData) baseObject).getSubno());
			pbcOriginalData.setVchdate(((PbcOriginalData) baseObject)
					.getVchdate());
			pbcOriginalData.setVcsession(((PbcOriginalData) baseObject)
					.getVcsession());
			pbcOriginalData.setSource(lineStr);
			pbcOriginalData.setState(2);
			map.put("noParse", pbcOriginalData);
		}
		return map;
	}

	/*ݿ�ķ���
	public void storeError(Object object) {
		System.out.println("store error.............");
		Session session = HibernateSessionFactory.getSession();
		IBaseDao baseDao = new BaseDaoJbpmImpl(session);
		baseDao.saveOrUpdate(object);
	}*/
	public List<Object> findObjects(Object object) {
		Session session = HibernateSessionFactory.getSession();
		IBaseDao dao=(IBaseDao)SpringHelper.getBean("baseDao");
		Transaction transaction = session.beginTransaction();
		List<Object> list = dao.findByExample(object);
		transaction.commit();
		return list;
	}
}
